package com.example.webview_interactive;

import android.os.Handler;
import android.os.Message;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by josan_tang on 9/5/17.
 */

public class MessageUtils {

    private static Map<String, Handler> sHandlerMap;
    private volatile static MessageUtils instance;

    private MessageUtils() {
        if (sHandlerMap == null) {
            sHandlerMap = new HashMap<>();
        }
    }

    public static MessageUtils getInstance() {
        if (instance == null ) {
            synchronized (MessageUtils.class) {
                if (instance == null) {
                    instance = new MessageUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 注册handler
     * @param key 注册handler使用的key
     * @param handler
     */
    public void registerHandler(String key, Handler handler) {
        sHandlerMap.put(key, handler);
    }

    /**
     * 反注册handler
     * @param key
     */
    public void unregisterHandler(String key) {
        if (sHandlerMap.containsKey(key)) {
            sHandlerMap.remove(key);
        }

    }

    /**
     * 发送全局的消息，实现类似广播的机制
     */
    public void sendOverallMessage(int what, Object obj) {
        Set<Map.Entry<String, Handler>> set = sHandlerMap.entrySet();
        for (Map.Entry<String, Handler> entry : set) {
            Handler handler = entry.getValue();
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            handler.sendMessage(msg);
        }
    }
}
